package com.ihk.toiletfinder;

import java.io.FileInputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.ihk.model.Parser;
import com.ihk.model.Toilet;

public class AddToiletActivity extends Activity implements LocationListener {

	Button addToiletButton;
	EditText caption;
	CheckBox barrierFree;
	
	LocationManager locationManager;
	double latitude = 0;
	double longitude = 0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_toilet);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

        caption = (EditText) findViewById(R.id.newToiletCaptionTextfield);
        
        barrierFree = (CheckBox) findViewById(R.id.newToiletBarrierFreeCheckbox);
        
        addToiletButton = (Button) findViewById(R.id.addToiletButton);
        addToiletButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				save();
			}
		});  
    }
    
    @Override
    public void onPause() {
      save();
      
      super.onPause();
    }
    
    private void save() {
    	Log.d("Saving", "AddToiletActivity.save() has been called");
    	Log.d("LocationInfo", "This Location will be saved: " + latitude + ", " + longitude);
    	
    	Toilet newToi = new Toilet();
    	newToi.nid = Parser.getMaxId() + 1;
    	newToi.latitude = (float) latitude;
    	newToi.longitude = (float) longitude;
    	newToi.body = caption.getText().toString();
    	if(barrierFree.isChecked()) {
    		newToi.type = "Handicap";
    	}
    	else {
    		newToi.type = "Unisex";
    	}
    	
    	if(Parser.getToilets() == null) {
			try {
				Parser.getInstance().parse(new FileInputStream(Parser.getFilePath()));
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
		
    	Parser.addNewToilet(newToi);
    	Parser.saveToiletsAsXML();
    	
		AddToiletActivity.this.startActivity(new Intent(AddToiletActivity.this, OpenStreetMapActivity.class));
		finish();
    }

	@Override
	public void onLocationChanged(Location loc) {
		Log.d("LocationChanged", "Location was updated!");
		latitude = loc.getLatitude();
		longitude = loc.getLongitude();
	}

	@Override
	public void onProviderDisabled(String arg0) { }

	@Override
	public void onProviderEnabled(String arg0) { }

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) { }
}
